package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.ResponseObject.PaintResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.MyReportService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.StationtResponseReport.StationtResponseReport;
import com.ugoodtech.mdcc.core.domain.TechColorAuditingReports.TechColorAuditingReports;
import com.ugoodtech.mdcc.core.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyReportServiceImpl implements MyReportService {

    private static final Logger logger = LoggerFactory.getLogger(MyReportServiceImpl.class);

    @Autowired
    private StationLeanPaintReportRepository stationLeanPaintReportRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Autowired
    private StationColorReportTempRepository stationColorReportTempRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Override
    public JsonResponse getMyPaintReport(User user, String type, Pageable pageable) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
        builder.and(qStationReport.user.id.eq(user.getId()));
        Sort sort = new Sort(Sort.Direction.DESC,  "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReportList = stationReportRepository.findAll(builder, pageable);
        List<PaintResponse> paintResponseList = new ArrayList<>();
        for (StationReport report : stationReportList) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            PaintResponse paintResponse = new PaintResponse(report, true, userProfile.getRealName());
            User editUser = report.getEditUser();
            if (editUser != null) {
                userProfile = userProfileRepository.findByUserId(editUser.getId());
                paintResponse.setEditUserName(userProfile.getRealName());
            }
            paintResponseList.add(paintResponse);
        }
        Page<PaintResponse> paintResponsePage = new PageImpl(paintResponseList, pageable, stationReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(paintResponsePage);
    }

    /**
     * 获取我的精益钣金报告
     *
     * @param userId   用户ID
     * @param pageable 分页
     * @param type     报告状态
     * @return
     */
    @Override
    public Page<StationtResponseReport> getStationLeanPaintReport(Long userId, Pageable pageable, String type) {
        QStationLeanPaintReport qStationLeanPaintReport = QStationLeanPaintReport.stationLeanPaintReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationLeanPaintReport.deleted.eq(false));
        builder.and(qStationLeanPaintReport.user.id.eq(userId));
        builder.and(qStationLeanPaintReport.type.eq(type));
        Page<StationLeanPaintReport> page = stationLeanPaintReportRepository.findAll(builder, pageable);
        List<StationLeanPaintReport> list = page.getContent();
        List<StationtResponseReport> stationtResponseReportList = new ArrayList<>();
        for (StationLeanPaintReport report : list) {
            StationtResponseReport responseReport = new StationtResponseReport();
            responseReport.setReportId(report.getId());
            responseReport.setDateTime(report.getCreationTimeStr());
            responseReport.setStationName(report.getStation().getName());
            QUserProfile qUserProfile = QUserProfile.userProfile;
            builder.and(qUserProfile.user.id.eq(userId));
            UserProfile userProfile = null;
            try {
                userProfile = userProfileRepository.findOne(builder);
                responseReport.setUserName(userProfile.getRealName());
                if (userProfile == null) {
                    responseReport.setUserName("");
                }
            } catch (Exception e) {
                responseReport.setUserName("");
            }
            stationtResponseReportList.add(responseReport);
        }
        Page<StationtResponseReport> stationtResponseReport = new PageImpl<StationtResponseReport>(stationtResponseReportList, pageable, page.getTotalElements());
        return stationtResponseReport;
    }

    /**
     * 计划中的常规服务报告列表
     *
     * @param user
     * @param pageable
     * @return
     */
    @Override
    public JsonResponse getPlanServiceReport(User user, Pageable pageable) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.user.id.eq(user.getId()));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> serviceReportList = stationReportRepository.findAll(builder, pageable);
        List<Long> ids = new ArrayList<>();
        for (StationReport report : serviceReportList.getContent()) {
            ids.add(report.getId());
        }

        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.questionId.eq(156L));
        builder.and(qStationRegularServiceReport.answerId.eq("354"));
        builder.and(qStationRegularServiceReport.stationReport.id.in(ids));
        List<StationRegularServiceReport> reportPage = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder, sort);
        List<TechColorAuditingReports> responsePlanReport = toReponse(reportPage);
        Page<TechColorAuditingReports> page = new PageImpl(responsePlanReport, pageable, serviceReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 封装计划中的常规报告
     *
     * @param reportPage
     * @return
     */
    private List<TechColorAuditingReports> toReponse(List<StationRegularServiceReport> reportPage) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
        UserProfile userProfile = null;
        String province = "";
        String city = "";
        String stationName = "";
        Station station = null;
        List<TechColorAuditingReports> techColorAuditingReportsList = new ArrayList<>();
        for (StationRegularServiceReport report : reportPage) {
            TechColorAuditingReports responseReport = new TechColorAuditingReports();
            responseReport.setId(report.getStationReport().getId());
            responseReport.setUserType(report.getStationReport().getUserType());
            responseReport.setImprovementTime(report.getStationReport().getImprovementTime());
            if (report.getStationReport().getStation() != null) {
                responseReport.setStationId(report.getStationReport().getStation().getId());
            }
            responseReport.setDateTime(simpleDateFormat.format(report.getStationReport().getUpdateTime()));
            if (report.getStationReport().getUser() != null) {
                userProfile = userProfileRepository.findByUserId(report.getStationReport().getUser().getId());
                responseReport.setUserName(userProfile.getRealName());
            } else {
                responseReport.setUserName("暂无");
            }

            if (report.getStationReport().getStation() != null) {
                station = report.getStationReport().getStation();
                if (StringUtils.isNotEmpty(station.getProvince())) {
                    province = station.getProvince();
                }
                if (StringUtils.isNotEmpty(station.getName())) {
                    stationName = station.getName();
                }
                if (StringUtils.isNotEmpty(station.getCity())) {
                    city = station.getCity();
                    if (province.equals(city)) {
                        responseReport.setStationName(province + stationName);
                    } else {
                        responseReport.setStationName(province + city + stationName);
                    }
                }
            } else {
                responseReport.setStationName("暂无");
            }
            techColorAuditingReportsList.add(responseReport);
        }
        return techColorAuditingReportsList;
    }


    /**
     * 获取我的报告
     *
     * @param user
     * @param pageable
     * @param category
     * @return
     */
    @Override
    public JsonResponse getMyReport(User user, Pageable pageable, String category) {
        Integer pageNum = pageable.getPageNumber();
        Integer pageSize = pageable.getPageSize();
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.user.id.eq(user.getId()));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(category));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReport> stationReports = stationReportRepository.findAll(builder, pageable);
        List<Long> ids = new ArrayList<>();
        for (StationReport report : stationReports.getContent()) {
            ids.add(report.getId());
        }

        QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
        builder = new BooleanBuilder();
        builder.and(qStationRegularServiceReport.deleted.eq(false));
        builder.and(qStationRegularServiceReport.enabled.eq(true));
        builder.and(qStationRegularServiceReport.questionId.eq(156L));
        builder.and(qStationRegularServiceReport.answerId.ne("354"));
        builder.and(qStationRegularServiceReport.stationReport.id.in(ids));
        List<StationRegularServiceReport> reportPage = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(builder, sort);
        List<TechColorAuditingReports> responsePlanReport = toReponse(reportPage);
        Page<TechColorAuditingReports> page = new PageImpl(responsePlanReport, pageable, stationReports.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    @Override
    public JsonResponse getMyAuditReport(User user, Pageable pageable) {
        QAuditReport qAuditReport = QAuditReport.auditReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditReport.deleted.eq(false));
        builder.and(qAuditReport.enabled.eq(true));
        builder.and(qAuditReport.user.id.eq(user.getId()));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        List<AuditReport> auditReportList = (List<AuditReport>) auditReportRepository.findAll(builder);
        return null;
    }

    @Override
    public JsonResponse getMyUnFinshedReport(User user, Pageable pageable, String category) {
        QStationReportTemp unFinshed = QStationReportTemp.stationReportTemp;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(unFinshed.deleted.eq(false));
        builder.and(unFinshed.enabled.eq(true));
        builder.and(unFinshed.user.id.eq(user.getId()));
        builder.and(unFinshed.reportCategory.eq(category));
        builder.and(unFinshed.reportType.eq(Constants.REPORT_TYPE_UNFINSHED));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<StationReportTemp> stationReportUnFinsheds = stationReportUnFinshedRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> colorAuditingReports = toUnFinshed(stationReportUnFinsheds.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(colorAuditingReports, pageable, stationReportUnFinsheds.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    private List<TechColorAuditingReports> toUnFinshed(List<StationReportTemp> stationReports) {
        List<TechColorAuditingReports> reportsList = new ArrayList<>();
        for (StationReportTemp report : stationReports) {
            logger.info("报告的类型为:" + report.getReportCategory());
            TechColorAuditingReports techColorAuditingReports = new TechColorAuditingReports();
            if (report.getStation() != null) {
                techColorAuditingReports.setStationId(report.getStation().getId());
            }
            if (report.getTemporaryStationId() != null && report.getTemporaryStationId() != 0) {
                techColorAuditingReports.setTemporaryStationId(report.getTemporaryStationId());
            }
            if (report.getReportCategory().equals(Constants.PAINT_REPORT)) {
                Long stationId = report.getStation().getId();
                QStationReport qStationReport = QStationReport.stationReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.id.eq(stationId));
                builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
                try {
                    Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
                    Pageable pageable = new PageRequest(0, 1, sort);
                    List<StationReport> stationReportList = stationReportRepository.findAll(builder, pageable).getContent();
                    if (stationReportList != null && stationReportList.size() > 0) {
                        techColorAuditingReports.setPaintRportId(stationReportList.get(0).getId());
                    }
                } catch (Exception e) {
                    logger.info("老数据，存在多条精益钣喷报告");
                }
            }
            techColorAuditingReports.setId(report.getId());
            if (report.getReportCategory().equals(Constants.TECHCOLOR_REPORT)) {
                logger.info("技术颜色报告ID:" + report.getId());
                StationColorReportTemp province = stationColorReportTempRepository.selectAnswerByQuestion(report.getId(), 173L);
                StationColorReportTemp city = stationColorReportTempRepository.selectAnswerByQuestion(report.getId(), 174L);
                StationColorReportTemp temp = stationColorReportTempRepository.selectAnswerByQuestion(report.getId(), 175L);
                String shenfeng = "";
                String chengshi = "";
                String stationName = "";
                if (province != null && StringUtils.isNotEmpty(province.getAnswerOther())) {
                    shenfeng = province.getAnswerOther();
                }
                if (temp != null && StringUtils.isNotEmpty(temp.getAnswerOther())) {
                    stationName = temp.getAnswerOther();
                }
                if (city != null && StringUtils.isNotEmpty(city.getAnswerOther())) {
                    chengshi = city.getAnswerOther();
                    if (shenfeng.equals(chengshi)) {
                        techColorAuditingReports.setStationName(shenfeng + stationName);
                    } else {
                        techColorAuditingReports.setStationName(shenfeng + chengshi + stationName);
                    }
                }
            } else {
                if (report.getStation() != null) {
                    String province = "";
                    String city = "";
                    String stationName = "";
                    if (StringUtils.isNotEmpty(report.getStation().getProvince())) {
                        province = report.getStation().getProvince();
                    }
                    if (StringUtils.isNotEmpty(report.getStation().getName())) {
                        stationName = report.getStation().getName();
                    }
                    if (StringUtils.isNotEmpty(report.getStation().getCity())) {
                        city = report.getStation().getCity();
                        if (province.equals(city)) {
                            techColorAuditingReports.setStationName(province + stationName);
                        } else {
                            techColorAuditingReports.setStationName(province + city + stationName);
                        }
                    }
                    logger.info("维修站名称为:" + province + city + stationName);
                } else {
                    logger.info(report.getReportCategory() + "报告没有维修站！！！！");
                    techColorAuditingReports.setStationName("");
                }
            }

            techColorAuditingReports.setUserType(report.getUserType());
            techColorAuditingReports.setDateTime(report.getUpdateTimeStr());
            if (report.getStation() != null && report.getStation().getId() != null && report.getStation().getId() != 0) {
                techColorAuditingReports.setStationId(report.getStation().getId());
            } else {
                techColorAuditingReports.setStationId(null);
            }
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            if (userProfile == null) {
                techColorAuditingReports.setUserName("默认的名字");
            } else {
                techColorAuditingReports.setUserName(userProfile.getRealName());
            }
            if (report.getReportCategory().equals(Constants.SERVICE_REPORT)) {
                StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(report.getId(), 155L);
                if (regularServiceReport == null) {
                    techColorAuditingReports.setTarget("");
                } else {
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String idStr : regularServiceReport.getAnswerId().split(",")) {
                        String targer = questionAnswerOptionRepository.findOne(Long.valueOf(idStr)).getName();
                        if (StringUtils.isNotEmpty(targer)) {
                            stringBuffer.append(targer + ",");
                        }
                    }
                    techColorAuditingReports.setTarget(stringBuffer.toString());
                }
            }
            reportsList.add(techColorAuditingReports);
        }
        return reportsList;
    }

    /**
     * 封装返回类--改
     *
     * @param stationReports
     * @return
     */
    private List<TechColorAuditingReports> toResponseVO(List<StationReport> stationReports) {
        List<TechColorAuditingReports> reportsList = new ArrayList<>();
        for (StationReport report : stationReports) {
            TechColorAuditingReports techColorAuditingReports = new TechColorAuditingReports();
            techColorAuditingReports.setId(report.getId());
            techColorAuditingReports.setFollowed(report.isIsfollowed());
            if (report.getStation() == null || report.getStation().getName() == null) {
                techColorAuditingReports.setStationName("");
            } else {
                String province = "";
                String city = "";
                String stationName = "";
                if (StringUtils.isNotEmpty(report.getStation().getProvince())) {
                    province = report.getStation().getProvince();
                }
                if (StringUtils.isNotEmpty(report.getStation().getName())) {
                    stationName = report.getStation().getName();
                }
                if (StringUtils.isNotEmpty(report.getStation().getCity())) {
                    city = report.getStation().getCity();
                    if (province.equals(city)) {
                        techColorAuditingReports.setStationName(province + stationName);
                    } else {
                        techColorAuditingReports.setStationName(province + city + stationName);
                    }
                }
            }
            if (StringUtils.isNotEmpty(report.getDeparmentIds())) {
                techColorAuditingReports.setFollowUp(true);
            }
            if (report.getStation() != null) {
                techColorAuditingReports.setStationId(report.getStation().getId());
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
            techColorAuditingReports.setDateTime(simpleDateFormat.format(report.getUpdateTime()));
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            if (userProfile == null) {
                techColorAuditingReports.setUserName("");
            } else {
                techColorAuditingReports.setUserName(userProfile.getRealName());
            }
            StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestion(report.getId(), 155L);
            if (regularServiceReport == null) {
                techColorAuditingReports.setTarget("");
            } else {
                String[] targerIds = regularServiceReport.getAnswerId().split(",");
                StringBuffer stringBuffer = new StringBuffer("");
                for (String id : targerIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                        if (questionAnswerOption != null&& questionAnswerOption.getName()!=null) {
                            String targer = questionAnswerOption.getName();
                            stringBuffer.append(targer);
                        }
                    }
                }
                techColorAuditingReports.setTarget(stringBuffer.toString());
            }
            reportsList.add(techColorAuditingReports);
        }
        return reportsList;
    }


}
